package com.chart.factory;

import java.awt.Color;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

import com.chart.ChartFactory;
import com.chart.vo.Chart;

public abstract class PieChartFactory<T extends Number> implements ChartFactory<T> {

	private Chart<T> chart;
	
	public Chart<T> getChart() {
		return chart;
	}

	public void setChart(Chart<T> chart) {
		this.chart = chart;
	}

	@Override
	public abstract void setData(Chart<T> chart);

	@Override
	public abstract Chart<T> createChart() throws IOException ;
	
	@Override
	public abstract Chart<T> createChart(Chart<T> chart) throws IOException ;

	protected PieDataset createDataset(Chart<T> chart) {
		DefaultPieDataset pieData = new DefaultPieDataset();  
		Map<String, T> dataMap = chart.getDataMap();
		
		for(String key : dataMap.keySet()) {
			T value = dataMap.get(key);
			pieData.setValue(key, value);
		}
		
	    return pieData;
	  }
	
	protected Chart<T> create(Plot plot) throws IOException, InstantiationException, IllegalAccessException {
		String title = (null == chart.getTitle()) ? "" : chart.getTitle();
		JFreeChart freeChart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, chart.isShowLegend());
		Color bgColor = (null == chart.getBgColor()) ? Color.WHITE : chart.getBgColor();
		freeChart.setBackgroundPaint(bgColor); //可选，设置图片背景色  
		ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
		HttpSession session = null;
		session = ServletActionContext.getRequest().getSession();
		//500是图片长度，300是图片高度  
		String filename = ServletUtilities.saveChartAsPNG(freeChart, 500, 300, info, session);  
		String graphURL = ServletActionContext.getRequest().getContextPath() 
				+ "/servlet/DisplayChart?filename=" + filename;
		chart.setFileNameOut(filename);
		chart.setGraphURLOut(graphURL);
		
		return chart;
	}
	
}
